package com.zjt.smart.mvp.model;

import com.zjt.smart.util.Json;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.BufferedSink;

public class BodyParam extends RequestBody{
    HashMap<String,Object> params;

    public BodyParam() {
        this(null);
    }
    public BodyParam(HashMap<String, Object> params) {
        this.params = params;
        if (this.params == null) this.params = new HashMap<>();
    }

    public void addParam(String key, Object value){
        params.put(key,value);
    }

    public Object getParam(String key){
        return params.get(key);
    }

    @Override
    public MediaType contentType() {
        MediaType type = MediaType.parse("application/json; charset=utf-8");
        return type;
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        Charset charset = Util.UTF_8;
        String jsonStr = Json.toJson(params);
        byte[] bytes = jsonStr.getBytes(charset);
        sink.write(bytes);
    }
}
